<template>
  <el-dialog
      v-model="dialogVisible"
      title="新增商品"
      width="700px"
      :before-close="handleCloseDialog"
  >
    <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="120px"
        class="product-add-form"
    >
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="商品编号" prop="code">
            <div class="product-add-form-code-wrapper">
              <el-input
                  v-model="addForm.code"
                  placeholder="请输入商品编号"
                  class="product-add-form-code-input"
              />
              <el-button
                  type="primary"
                  class="product-add-form-code-btn"
                  @click="generateRandomCode"
              >
                随机生成
              </el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品名称" prop="name">
            <el-input
                v-model="addForm.name"
                placeholder="请输入商品名称"
                class="product-add-form-input"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="品牌" prop="brand">
            <el-input
                v-model="addForm.brand"
                placeholder="请输入品牌"
                class="product-add-form-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="型号/规格" prop="model">
            <el-input
                v-model="addForm.model"
                placeholder="请输入型号/规格"
                class="product-add-form-input"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="单位" prop="unit">
            <el-input
                v-model="addForm.unit"
                placeholder="请输入单位"
                class="product-add-form-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类" prop="categoryId">
            <el-tree-select
                v-model="addForm.categoryId"
                :data="categoryTreeData"
                :render-after-expand="false"
                :check-strictly="true"
                placeholder="请选择分类"
                class="product-add-form-tree-select"
                :props="{
                  value: 'id',
                  label: 'name',
                  children: 'children'
                }"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="参考采购价" prop="purchasePrice">
            <el-input
                v-model.number="addForm.purchasePrice"
                placeholder="请输入参考采购价"
                class="product-add-form-input"
                type="number"
                :min="0"
                step="1"
                @input="handlePriceInput('purchasePrice', $event)"
            >
              <template #prefix>¥</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="默认销售价" prop="salePrice">
            <el-input
                v-model.number="addForm.salePrice"
                placeholder="请输入默认销售价"
                class="product-add-form-input"
                type="number"
                :min="0"
                step="1"
                @input="handlePriceInput('salePrice', $event)"
            >
              <template #prefix>¥</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="商品图片" prop="image">
        <el-upload
            class="product-add-form-upload"
            :action="uploadAction"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="handleUpload"
            accept="image/*"
        >
          <div v-if="addForm.image" class="product-add-form-upload-preview">
            <img :src="getImageDisplayUrl(addForm.image)" alt="商品图片" class="product-add-form-upload-preview-img" />
            <div class="product-add-form-upload-preview-mask">
              <el-icon class="product-add-form-upload-preview-mask-icon"><Edit /></el-icon>
            </div>
          </div>
          <div v-else class="product-add-form-upload-placeholder">
            <el-icon class="product-add-form-upload-placeholder-icon"><Plus /></el-icon>
            <div class="product-add-form-upload-placeholder-text">点击上传图片</div>
          </div>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="product-add-dialog-footer">
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {reactive, ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {getCategoriesTree} from "../../../api/categoryApi.js";
import {uploadImage} from "../../../api/fileApi.js";
import {addProduct} from "../../../api/productApi.js";

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

// 定义emits
const emits = defineEmits(['update:visible', 'success'])

// 对话框显示状态
const dialogVisible = ref(false)

// 表单引用
const addFormRef = ref()

// 分类树数据
const categoryTreeData = ref([])

// 上传地址（使用 fileApi 的方法，这里设置为空）
const uploadAction = ref('')

// 新增表单数据
const addForm = reactive({
  code: '',
  name: '',
  brand: '',
  model: '',
  unit: '',
  purchasePrice: null,
  salePrice: null,
  image: '',
  categoryId: null
})

// 表单验证规则
const addFormRules = reactive({
  code: [
    {required: true, message: '请输入商品编号', trigger: 'blur'},
    {min: 1, max: 50, message: '商品编号长度在 1 到 50 个字符', trigger: 'blur'}
  ],
  name: [
    {required: true, message: '请输入商品名称', trigger: 'blur'},
    {min: 1, max: 100, message: '商品名称长度在 1 到 100 个字符', trigger: 'blur'}
  ],
  unit: [
    {required: true, message: '请输入单位', trigger: 'blur'},
    {min: 1, max: 50, message: '单位长度在 1 到 50 个字符', trigger: 'blur'}
  ],
  categoryId: [
    {required: true, message: '请选择分类', trigger: 'change'}
  ]
})

// 监听visible变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    loadCategoryTree()
  }
})

// 监听dialogVisible变化，同步到父组件
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    emits('update:visible', false)
  }
})

// 关闭对话框
const handleCloseDialog = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  addForm.code = ''
  addForm.name = ''
  addForm.brand = ''
  addForm.model = ''
  addForm.unit = ''
  addForm.purchasePrice = null
  addForm.salePrice = null
  addForm.image = ''
  addForm.categoryId = null
}

// 提交表单
const handleSubmit = async () => {
  if (!addFormRef.value) return

  try {
    await addFormRef.value.validate()
    await addProduct(addForm)
    // 通知父组件操作成功
    emits('success', addForm)
    handleCloseDialog()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 加载分类树数据
const loadCategoryTree = async () => {
  try {
    const res = await getCategoriesTree()
    // 确保数据是数组格式，如果后端返回单个对象，需要包装为数组
    if (res && typeof res === 'object' && !Array.isArray(res)) {
      categoryTreeData.value = [res]
    } else if (Array.isArray(res)) {
      categoryTreeData.value = res
    } else {
      categoryTreeData.value = []
    }
  } catch (error) {
    console.error('加载分类树失败:', error)
    ElMessage.error('加载分类数据失败')
  }
}

// 处理价格输入
const handlePriceInput = (field, value) => {
  // 保留两位小数
  const numValue = parseFloat(value)
  if (!isNaN(numValue)) {
    addForm[field] = Math.round(numValue * 100) / 100
  } else {
    addForm[field] = null
  }
}

// 上传前检查
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  return true
}

// 手动上传处理
const handleUpload = async (options) => {
  const { file } = options

  try {
    // 调用 fileApi 的上传方法
    addForm.image = await uploadImage(file)
    ElMessage.success('图片上传成功')
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
  }
}

// 获取图片显示URL
const getImageDisplayUrl = (imagePath) => {
  // 通过后端接口访问本地文件
  if (imagePath) {
    return `/api/file/image?path=${encodeURIComponent(imagePath)}`
  }
  return imagePath
}

// 生成随机8位数字编码
const generateRandomCode = () => {
  // 生成8位随机数字编码
  const randomCode = Math.floor(Math.random() * 100000000).toString().padStart(8, '0')
  addForm.code = randomCode
  ElMessage.success('已生成随机编码: ' + randomCode)
}
</script>

<style scoped lang="scss">
.product-add {
  &-form {
    padding: 16px 0;

    &-code {
      &-wrapper {
        display: flex;
        gap: 8px;
        align-items: center;
      }

      &-input {
        flex: 1;
      }

      &-btn {
        flex: 0 0 auto;
        font-size: 12px;
        padding: 8px 12px;
        white-space: nowrap;
      }
    }

    &-input {
      width: 100%;
    }

    &-tree-select {
      width: 100%;
    }

    &-upload {
      width: 120px;
      height: 120px;

      &-preview {
        position: relative;
        width: 120px;
        height: 120px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        overflow: hidden;

        &:hover {
          border-color: #409eff;

          .product-add-form-upload-preview-mask {
            opacity: 1;
          }
        }

        &-img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        &-mask {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.5);
          display: flex;
          align-items: center;
          justify-content: center;
          opacity: 0;
          transition: opacity 0.3s;

          &-icon {
            font-size: 20px;
            color: #fff;
          }
        }
      }

      &-placeholder {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 120px;
        height: 120px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        transition: border-color 0.3s;

        &:hover {
          border-color: #409eff;
        }

        &-icon {
          font-size: 28px;
          color: #8c939d;
          margin-bottom: 8px;
        }

        &-text {
          font-size: 14px;
          color: #8c939d;
          text-align: center;
        }
      }
    }
  }

  &-dialog {
    &-footer {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
    }
  }
}
</style>
